/*
 * Designed and developed by 2017 skydoves (Jaewoong Eum)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.skydoves.colorpickerviewdemo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.skydoves.colorpickerview.AlphaTileView;
import com.skydoves.colorpickerview.ColorEnvelope;
import com.skydoves.colorpickerview.ColorPickerDialog;
import com.skydoves.colorpickerview.ColorPickerView;
import com.skydoves.colorpickerview.flag.BubbleFlag;
import com.skydoves.colorpickerview.flag.FlagMode;
import com.skydoves.colorpickerview.listeners.ColorEnvelopeListener;
import com.skydoves.colorpickerview.sliders.AlphaSlideBar;
import com.skydoves.colorpickerview.sliders.BrightnessSlideBar;
import com.skydoves.powermenu.OnMenuItemClickListener;
import com.skydoves.powermenu.PowerMenu;
import com.skydoves.powermenu.PowerMenuItem;

import java.io.FileNotFoundException;
import java.io.InputStream;

import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

  private ColorPickerView colorPickerView;

  private boolean FLAG_PALETTE = false;
  private boolean FLAG_SELECTOR = false;
  private boolean FLAG_LINEAR_PALETTE = true; // 控制是否使用线性调色板
  private boolean FLAG_BRIGHTNESS_SQUARE = false; // 控制亮度滑动条是否为方形模式

  private PowerMenu powerMenu;
  private final OnMenuItemClickListener<PowerMenuItem> powerMenuItemClickListener =
    new OnMenuItemClickListener<>() {
      @Override
      public void onItemClick(int position, PowerMenuItem item) {
        switch (position) {
          case 0: {
            palette();
            break;
          }
          case 1: {
            paletteFromGallery();
            break;
          }
          case 2:
            selector();
            break;
          case 3:
            dialog();
            break;
          case 4:
            togglePaletteType();
            break;
          case 5:
            toggleBrightnessMode();
            break;
        }
        powerMenu.dismiss();
      }
    };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    powerMenu = PowerMenuUtils.getPowerMenu(this, this, powerMenuItemClickListener);

    colorPickerView = findViewById(R.id.colorPickerView);
    BubbleFlag bubbleFlag = new BubbleFlag(this);
    bubbleFlag.setFlagMode(FlagMode.FADE);
    colorPickerView.setFlagView(bubbleFlag);
    colorPickerView.setColorListener(
      (ColorEnvelopeListener)
        (envelope, fromUser) -> {
          Timber.d("color: %s", envelope.getHexCode());
          setLayoutColor(envelope);
        });

    // attach alphaSlideBar
    final AlphaSlideBar alphaSlideBar = findViewById(R.id.alphaSlideBar);
    colorPickerView.attachAlphaSlider(alphaSlideBar);

    // attach brightnessSlideBar
    final BrightnessSlideBar brightnessSlideBar = findViewById(R.id.brightnessSlide);
    colorPickerView.attachBrightnessSlider(brightnessSlideBar);
    colorPickerView.setLifecycleOwner(this);
    
    // 添加测试按钮点击事件来验证修复
    findViewById(R.id.btn_test_initial_color).setOnClickListener(v -> testInitialColor());
  }

  /**
   * set layout color & textView html code
   *
   * @param envelope ColorEnvelope by ColorEnvelopeListener
   */
  @SuppressLint("SetTextI18n")
  private void setLayoutColor(ColorEnvelope envelope) {
    TextView textView = findViewById(R.id.textView);
    textView.setText("#" + envelope.getHexCode());

    AlphaTileView alphaTileView = findViewById(R.id.alphaTileView);
    alphaTileView.setPaintColor(envelope.getColor());
  }

  /**
   * shows the popup menu for changing options..
   */
  public void overflowMenu(View view) {
    powerMenu.showAsAnchorLeftTop(view);
  }
  
  /**
   * 切换亮度滑动条模式：长条模式或方形模式
   */
  private void toggleBrightnessMode() {
    final BrightnessSlideBar brightnessSlideBar = findViewById(R.id.brightnessSlide);
    if (FLAG_BRIGHTNESS_SQUARE) {
      // 切换回长条模式
      brightnessSlideBar.setSquareMode(false);
      brightnessSlideBar.setEnableBorder(true); // 长条模式启用边框
      // 可以调整长条模式的圆角
      brightnessSlideBar.setCornerRadius(0f);
    } else {
      // 切换到方形模式
      brightnessSlideBar.setSquareMode(true);
      brightnessSlideBar.setEnableBorder(false); // 方形模式禁用边框
      // 设置方形模式的圆角（直接使用10dp的像素值）
       float radius = 10f; // 10dp
       brightnessSlideBar.setCornerRadius(radius);
    }
    FLAG_BRIGHTNESS_SQUARE = !FLAG_BRIGHTNESS_SQUARE;
  }

  /**
   * changes palette image using drawable resource.
   */
  private void palette() {
    if (FLAG_PALETTE) {
      colorPickerView.setHsvPaletteDrawable();
    } else {
      colorPickerView.setPaletteDrawable(ContextCompat.getDrawable(this, R.drawable.palettebar));
    }
    FLAG_PALETTE = !FLAG_PALETTE;
  }
  
  /**
   * 切换调色板类型：线性彩虹条或圆形调色板
   */
  private void togglePaletteType() {
    if (FLAG_LINEAR_PALETTE) {
      // 切换回圆形调色板
      colorPickerView.setHsvPaletteDrawable();
    } else {
      // 切换到线性彩虹条调色板
      colorPickerView.setLinearPaletteDrawable();
    }
    FLAG_LINEAR_PALETTE = !FLAG_LINEAR_PALETTE;
  }

  /**
   * changes palette image from a gallery image.
   */
  private void paletteFromGallery() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, 1000);
  }

  /**
   * changes selector image using drawable resource.
   */
  private void selector() {
    if (FLAG_SELECTOR) {
      colorPickerView.setSelectorDrawable(ContextCompat.getDrawable(this, com.skydoves.colorpickerview.R.drawable.colorpickerview_wheel));
    } else {
      colorPickerView.setSelectorDrawable(ContextCompat.getDrawable(this, R.drawable.wheel_dark));
    }
    FLAG_SELECTOR = !FLAG_SELECTOR;
  }

  /**
   * shows ColorPickerDialog
   */
  private void dialog() {
    ColorPickerDialog.Builder builder =
      new ColorPickerDialog.Builder(this)
        .setTitle("ColorPicker Dialog")
        .setPreferenceName("Test")
        .setPositiveButton(
          getString(R.string.confirm),
          (ColorEnvelopeListener) (envelope, fromUser) -> setLayoutColor(envelope))
        .setNegativeButton(
          getString(R.string.cancel), (dialogInterface, i) -> dialogInterface.dismiss());
    builder.getColorPickerView().setFlagView(new BubbleFlag(this));
    builder.show();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // user choose a picture from gallery
    if (requestCode == 1000 && resultCode == RESULT_OK) {
      try {
        final Uri imageUri = data.getData();
        if (imageUri != null) {
          final InputStream imageStream = getContentResolver().openInputStream(imageUri);
          final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
          Drawable drawable = new BitmapDrawable(getResources(), selectedImage);
          colorPickerView.setPaletteDrawable(drawable);
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 测试彩虹条模式下的initialColor功能
   */
  private void testInitialColor() {
    Timber.d("开始测试初始颜色功能");
    
    // 确保当前是彩虹条模式
    if (!FLAG_LINEAR_PALETTE) {
      Timber.d("切换到彩虹条模式");
      togglePaletteType();
    } else {
      Timber.d("已经是彩虹条模式");
    }
    
    // 测试不同颜色的initialColor
    try {
      // 随机选择一个颜色进行测试（这里选择绿色）
      int testColor = 0xFF00FF00; // 绿色
      Timber.d("测试设置初始颜色: #%08X", testColor);
      
      // 直接调用setInitialColor测试
      Timber.d("调用setInitialColor");
      colorPickerView.setInitialColor(testColor);
      Timber.d("setInitialColor调用完成");
      
      // 增加一个短暂延迟后再次设置不同的颜色，以便观察变化
      new android.os.Handler().postDelayed(() -> {
        try {
          int testColor2 = 0xFF0000FF; // 蓝色
          Timber.d("延迟后设置颜色: #%08X", testColor2);
          colorPickerView.setInitialColor(testColor2);
        } catch (Exception e) {
          Timber.e(e, "延迟设置颜色时出错");
        }
      }, 1000);
      
    } catch (Exception e) {
      Timber.e(e, "测试初始颜色时出错");
    }
  }
  
  @Override
  public void onBackPressed() {
    if (powerMenu.isShowing()) {
      powerMenu.dismiss();
    } else {
      super.onBackPressed();
    }
  }
}
